package nio;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;

public class ReadAndWriteArray {

	public static void main(String[] args) {
		File filein = new File("file/arrayin.txt");
		File fileout = new File("file/arrayout-nio.txt");
		try {
			RandomAccessFile fin = new RandomAccessFile(filein, "r");
			FileChannel inChannel = fin.getChannel();
			
			ByteBuffer buf = ByteBuffer.allocate(48);
			int bytesRead = inChannel.read(buf);
			String content="";
			while(bytesRead != -1){
				buf.flip();
				byte a[] = new byte[buf.remaining()];
				buf.get(a);
				content += new String(a);
				buf.clear();
				bytesRead = inChannel.read(buf);
			}
			fin.close();
			String data[] = content.split("\n");
			String num[] = data[0].split(" ");
			int m = Integer.parseInt(num[0]);
			int n = Integer.parseInt(num[1]);
			int arr[][] = new int[m][n];
			for(int i=1;i<m+1;i++){
				num = data[i].split(" ");
				for(int j=0;j<n;j++)
					arr[i-1][j] = Integer.parseInt(num[j]);
			}
			for(int i=0;i<m;i++){
				for(int j=0;j<n;j++)
					System.out.print(arr[i][j]+" ");
				System.out.println();
			}
			
			FileOutputStream fout = new FileOutputStream(fileout);
			FileChannel outChannel = fout.getChannel();
			ByteBuffer bufout = ByteBuffer.allocate(1024);
			String out = "";
			out += m + " " + n + " \n";
			for(int i=0;i<m;i++){
				for(int j=0;j<n;j++)
					out+=arr[i][j] + " ";
				out+="\n";
			}
			System.out.println(out);
			bufout.put(out.getBytes());
			bufout.flip();
			outChannel.write(bufout);
			fout.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
